package com.fitbet.wechat.processor.impl;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.storage.Qiniu;
import com.demo2do.core.storage.handler.AbstractQiniuStorageProcessor;
import com.demo2do.core.storage.rao.QiniuRao;
import com.demo2do.core.storage.utils.QiniuUtils;
import com.demo2do.core.utils.StringUtils;
import com.fitbet.wechat.processor.ImageProcessor;

/**
 *
 * @author Ark
 *
 */
@Component("imageProcessor")
public class ImageProcessorImpl extends AbstractQiniuStorageProcessor implements ImageProcessor {

    private static final Logger logger = LoggerFactory.getLogger(ImageProcessorImpl.class);
    
    @Value("#{cloud['qiniu.host']}")
    private String host;
    
    @Rao
    private QiniuRao qiniuRao;
    
    /* (non-Javadoc)
     * @see com.yuanwyl.wechat.processor.ImageProcessor#fetch(java.lang.String)
     */
    public String fetch(String fetchUrl) {
        
        String bucket = QiniuUtils.encode(super.config.getBucket());
        
        String fetch = StringUtils.connect("/fetch/", QiniuUtils.encode(fetchUrl), "/to/", bucket);
        
        String url = StringUtils.connect(Qiniu.KODO.FETCH, fetch);
        String authorization = super.authorize(fetch);
        logger.trace("#fetch - start fetching resource with url[{}] and authorization[{}]", url, authorization);
        
        HttpResult httpResult = qiniuRao.fetch(url, authorization);
        
        if(httpResult.getStatus() == 200) {
            
            Map<String, Object> response = httpResult.describe();
            
            if(response.containsKey("key")) {
                
                String key = response.get("key").toString();
                String absolutePath = StringUtils.connect(host, "/", key);
                logger.trace("#fetch - get absolute path is [{}]", absolutePath);
                
                return absolutePath;
            }
            
            throw BusinessException.newInstance("500", "获取远程资源失败");
            
        } 
        
        throw QiniuUtils.toBusinessException(httpResult);
        
    }

}
